package com.daykw.xiaohongshu.task.thread;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.log4j.Logger;
import org.codehaus.plexus.util.StringUtils;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.xiaohongshu.http.HttpBase;
import com.daykw.xiaohongshu.model.TAuthorNextTask;
import com.daykw.xiaohongshu.model.TAuthorTask;
import com.daykw.xiaohongshu.util.CommonUtils;
import com.daykw.xiaohongshu.util.SpringContextHolder;

public class AuthorJobThread implements Runnable {

	private static Logger logger = Logger.getLogger(AuthorJobThread.class);
	private TAuthorTask task;

	public AuthorJobThread(TAuthorTask task) {
		this.task = task;
	}

	@Override
	public void run() {
		NutDao dao = SpringContextHolder.getBean("dao");
		try {
			dao.update(TAuthorTask.class, Chain.make("status", 1), Cnd.where("id", "=", task.getId()));
			String url = "http://www.xiaohongshu.com/user/profile/" + task.getUser_id()+"?_at=9b7f9eb29dcc07dc40eb14675f2b68f99ca81" ;
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Accept", "application/json, text/plain, */*");
			headers.put("Accept-Encoding", "gzip, deflate, sdch");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("Cache-Control", "max-age=0");
			headers.put("Cookie",
					"xhsTrackerId=9ed6751b-39ee-4682-c610-b1f96d102595; exp_ids=m_TestA-ctl2; Hm_lvt_d0ae755ac51e3c5ff9b1596b0c09c826=1515084426; Hm_lpvt_d0ae755ac51e3c5ff9b1596b0c09c826=1515084426; Hm_lvt_9df7d19786b04345ae62033bd17f6278=1515084426; Hm_lpvt_9df7d19786b04345ae62033bd17f6278=1515084430; xhs_spid.5dde=5fc5a7b7c9148948.1515084421.1.1515084433.1515084421.951e5781-af93-46c0-8994-797318048a51; xhs_spses.5dde=*");
			headers.put("Host", "www.xiaohongshu.com");
			headers.put("Upgrade-Insecure-Requests", "1");
			headers.put("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
			// String html = http.request(url, "utf-8",
			// headers,ip,port).getResult();
			String html = http.get(url, "utf-8", headers, true);
			
			while (StringUtils.isNotEmpty(html) && html.equals("fail")) {
//				int c = CommonUtils.getRandomNum();
//				if (c <= 1) {
//					html = new HttpBase().fget(url, "utf-8", headers, true);
//
//				} else {
					html = new HttpBase().get(url, "utf-8", headers, true);
//				}
//
//				if (html.indexOf("Concurrent number exceeds limit") >= 0) {
//					html = new HttpBase().get(url, "utf-8", headers, true);
//				}
				if (html.equals("404")) {
					break;
				}
				// TimeUnit.SECONDS.sleep(3);
				// logger.info("##########请求返回Fail##########");
			}
			if(html.equals("404")){
				dao.update(TAuthorTask.class, Chain.make("status", 5), Cnd.where("id", "=", task.getId()));
				return;
			}
			if(html.contains("error404")) {
				dao.update(TAuthorTask.class, Chain.make("status", 5), Cnd.where("id", "=", task.getId()));
				return;
			}
			
			String userInfo = null;
			try{
				userInfo = CommonUtils.subString("\"UserDetail\":", ",\"notesDetail", html);
			}catch(Exception e){
				dao.update(TAuthorTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
				return;
			}
			userInfo = userInfo.replaceAll("\\\\u002F", "/");
			JSONObject json = new JSONObject(userInfo);
			Document doc = Jsoup.parse(html);
			task.setUrl(url);
			task.setNick(json.getString("nickname"));
			task.setFollows_num(json.getLong("follows"));
			task.setFans_num(json.getLong("fans"));
			task.setLiked_num(json.getLong("liked"));
			task.setLocation(json.getString("location"));
			task.setLevel(doc.select("span.level").text().replace("等级: ", ""));
			task.setRemark(json.getString("desc"));
			task.setNote_num(json.getLong("notes"));
			task.setBoard_num(json.getLong("boards"));
			task.setStatus(2);
			task.setGender(json.getInt("gender"));
			task.setImageb(json.getString("imageb"));
			task.setJson(userInfo);
			task.setUpdate_time(new Date());
			dao.update(task);
			long count = (task.getNote_num() - 1) / 10 + 1;
			TAuthorNextTask knt;
			for (int i = 1; i <= count; i++) {
				knt = new TAuthorNextTask();
				knt.setCreate_time(new Date());
				knt.setUser_id(task.getUser_id());
				knt.setPage_index(i);
				knt.setStatus(0);
				try {
					dao.fastInsert(knt);
				} catch (Exception e) {
					// e.printStackTrace();
					// logger.error("插入TAuthorNextTask失败.", e);
				}
			}
			logger.info("处理成功:" + url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("处理TAuthorTask任务失败.", e);
			task.setStatus(3);
			dao.update(task);
		}

	}

	public String StringFilter(String str) throws PatternSyntaxException {
		// 只允许字母和数字
		// String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}
	
	
	public static void main(String args[])throws Exception{
		String v = "7.3万";
		System.out.println(parse(v));
	}
	
	
	private static Long parse(String v){
		if(StringUtils.isEmpty(v)){
			return 0L;
		}
		v = v.replace("·", "");
		if(v.contains("万")){
			double d = Double.valueOf(v.replace("万", ""))*10000;
			return ((long)d);
		}
		if(StringUtils.isNumeric(v)){
			return Long.valueOf(v);
		}
		return 0L;
	}
	

}
